package com.north.light.androidutils.recyclerview.scrollview.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Guideline;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.north.light.androidutils.R;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * FileName: BannerPicView
 * Author: lzt
 * Date: 2022/10/17 11:50
 * 图片banner view
 */
public class BannerPicView extends RecyclerView {

    private List<BannerPicInfo> mPicList = new ArrayList<>();
    private BannerPicAdapter mPicAdapter;
    private BannerPicLoadListener mPicLoadListener;
    private DataPositionListener mPosListener;


    //自动滚动相关
    private static final int HANDLER_AUTO_SCROLL = 0x0001;
    private static final long HANDLER_AUTO_SCROLL_INTERVAL = 4000;
    private Handler mUIHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_AUTO_SCROLL:
                    //rv进行滚动
                    if (!mTouching && mAutoScroll && (mPicList != null && mPicList.size() != 0)) {
                        //用户没有触摸且自动滑动
                        if (mCurrentPos >= mPicList.size()) {
                            //尽头了，回到第一个
                            mCurrentPos = 0;
                            scrollToPosition(0);
                        } else {
                            //下一个
                            mCurrentPos = mCurrentPos + 1;
                            smoothScrollToPosition(mCurrentPos);
                            notifyPosition(mCurrentPos, mPicList.size());
                        }
                    }
                    mUIHandler.sendEmptyMessageDelayed(HANDLER_AUTO_SCROLL, HANDLER_AUTO_SCROLL_INTERVAL);
                    break;
            }
        }
    };
    //是否自动滚动
    private boolean mAutoScroll = false;
    //用户是否触摸中
    private boolean mTouching = false;
    //当前的位置
    private int mCurrentPos = 0;

    @Override
    protected void onDetachedFromWindow() {
        canAutoScroll(false);
        super.onDetachedFromWindow();
    }

    public BannerPicView(@NonNull Context context) {
        super(context);
        init();
    }

    public BannerPicView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BannerPicView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    @Override
    public boolean onTouchEvent(MotionEvent e) {
        int action = e.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mTouching = true;
                break;
            case MotionEvent.ACTION_MOVE:
                mTouching = true;
                break;
            case MotionEvent.ACTION_CANCEL:
                mTouching = false;
                break;
            case MotionEvent.ACTION_UP:
                mTouching = false;
                break;
        }
        return super.onTouchEvent(e);
    }

    private void init() {
        setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
        setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.HORIZONTAL, false));
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper() {

            // 在 Adapter的 onBindViewHolder 之后执行
            @Override
            public int findTargetSnapPosition(LayoutManager layoutManager, int velocityX, int velocityY) {
                int targetPos = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
                Log.d("findTargetSnapPosition", "---findTargetSnapPosition---targetPos: " + targetPos);
                mCurrentPos = targetPos;
                notifyPosition(targetPos + 1, mPicList.size());
                return targetPos;

            }

            // 在 Adapter的 onBindViewHolder 之后执行
            @Nullable
            @Override
            public View findSnapView(LayoutManager layoutManager) {
                return super.findSnapView(layoutManager);
            }
        };
        pagerSnapHelper.attachToRecyclerView(this);
        mPicAdapter = new BannerPicAdapter(getContext());
        setAdapter(mPicAdapter);
    }

    //adapter
    private static class BannerPicAdapter extends Adapter<BannerPicAdapter.PicHolder> {
        private List<BannerPicInfo> mDataList = new ArrayList<>();
        private BannerPicLoadListener mPicLoadListener;
        private Context mContext;


        public void setPicListener(BannerPicLoadListener listener) {
            this.mPicLoadListener = listener;
        }

        public void setData(List<BannerPicInfo> data) {
            this.mDataList = data;
            notifyDataSetChanged();
        }

        public BannerPicAdapter(Context context) {
            this.mContext = context;
        }

        @NotNull
        @Override
        public PicHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_banner_pic_view,
                    parent, false);
            return new PicHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull PicHolder holder, int position) {
            BannerPicInfo picInfo = mDataList.get(position);
            if (picInfo != null) {
                String picUrl = picInfo.getPicUrl();
                if (mPicLoadListener != null && !TextUtils.isEmpty(picUrl)) {
                    String ivTag = picInfo + String.valueOf(position);
                    holder.ivPic.setTag(ivTag);
                    mPicLoadListener.load(holder.ivPic, picUrl, new BannerPicSizeCallback() {
                        @Override
                        public void size(String url, int width, int height, Bitmap bitmap) {
                            //设置控件宽高，然后再设置bitmap
                            if (holder.ivPic.getTag() instanceof String) {
                                String ivOldTag = (String) holder.ivPic.getTag();
                                if (!ivOldTag.equals(ivTag)) {
                                    return;
                                }
                                //设置图片数据
                                holder.ivPic.setScaleType(ImageView.ScaleType.CENTER_CROP);
                                holder.clRoot.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        boolean isLandScope = (width >= height);
                                        if (!isLandScope) {
                                            //竖屏
                                            holder.glTop.setGuidelinePercent(picInfo.getVerTopRate());
                                            holder.glBottom.setGuidelinePercent(picInfo.getVerBottomRate());
                                        } else {
                                            //横屏
                                            //动态设置高度
                                            int screenSize = getScreenWidth(mContext);
                                            float trainHeight = (screenSize * 1.0f * picInfo.getHorWHRate());
                                            holder.glTop.setGuidelinePercent(picInfo.getHorTopRate());
                                            float heightRate = trainHeight / holder.clRoot.getMeasuredHeight() * 1.0f;
                                            float trainRate = picInfo.getHorTopRate() + (heightRate);
                                            holder.glBottom.setGuidelinePercent(trainRate);
                                        }
                                        holder.ivPic.setImageBitmap(bitmap);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }

        public static class PicHolder extends ViewHolder {
            ImageView ivPic;
            Guideline glTop;
            Guideline glBottom;
            ConstraintLayout clRoot;

            public PicHolder(@NonNull @NotNull View itemView) {
                super(itemView);
                ivPic = itemView.findViewById(R.id.iv_pic);
                glTop = itemView.findViewById(R.id.gl_top);
                glBottom = itemView.findViewById(R.id.gl_bottom);
                clRoot = itemView.findViewById(R.id.cl_root);
            }
        }
    }


    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        //创建了一张白纸
        DisplayMetrics outMetrics = new DisplayMetrics();
        //给白纸设置宽高
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 通知位置
     */
    private void notifyPosition(int pos, int total) {
        if (mPicList == null || mPicList.size() == 0) {
            //没有数据则不需要回调
            return;
        }
        if (this.mPosListener != null) {
            this.mPosListener.pos(pos, total);
        }
    }

    private void notifyEmpty() {
        if (this.mPosListener != null) {
            this.mPosListener.empty();
        }
    }

    //外部调用方法-----------------------------------------------------------------------------------


    public void canAutoScroll(boolean scroll) {
        this.mAutoScroll = scroll;
        this.mUIHandler.removeCallbacksAndMessages(null);
        if (scroll) {
            mUIHandler.sendEmptyMessageDelayed(HANDLER_AUTO_SCROLL, HANDLER_AUTO_SCROLL_INTERVAL);
        }
    }

    /**
     * 设置数据
     */
    public void setData(List<BannerPicInfo> bannerPicInfo, BannerPicLoadListener bannerPicLoadListener) {
        this.mPicLoadListener = bannerPicLoadListener;
        this.mPicList = bannerPicInfo;
        if (mPicList == null || mPicList.size() == 0) {
            mPicList = new ArrayList<>();
            notifyEmpty();
        } else {
            notifyPosition(1, mPicList.size());
        }
        //刷新数据----------------------------------------------
        if (mPicAdapter != null) {
            mPicAdapter.setPicListener(mPicLoadListener);
            mPicAdapter.setData(mPicList);
        }
    }


    /**
     * 位置监听
     */
    public interface DataPositionListener {
        void pos(int curPos, int total);

        void empty();
    }

    public void setDataPositionListener(DataPositionListener listener) {
        this.mPosListener = listener;
    }

    public void removeDataPositionListener() {
        this.mPosListener = null;
    }


}
